package com.eascs.web.o2o.scheduler.history;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.util.IoUtil;
import com.eascs.notify.email.EmailSender;
import com.eascs.notify.email.entity.EmailContentEntity;
import com.eascs.notify.email.entity.EmailSourceSetting;
import com.eascs.web.o2o.report.util.BankRowWriteHandler;
import com.eascs.web.o2o.scheduler.dao.BaseDao;
import com.eascs.web.o2o.scheduler.dao.ServiceDao;
import com.eascs.web.o2o.scheduler.entity.BpPerformanceTargetEntity;
import com.eascs.web.o2o.scheduler.entity.BpPerformanceTaskEntity;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * 全国各省区品牌贷投放情况：月度和季度任务
 * Created by user on 2017/2/16.
 */
@Service
public class BpPerformanceService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Value("${msg.report.bp.outpath}")
	private String outpath;    //BP报表存储地址

	@Inject
	BaseDao baseDao;

	@Inject
	ServiceDao serviceDao;

	@Autowired
	private EmailSender emailSender;

	@Autowired
	EmailSourceSetting emailSourceSetting;

	/**
	 * 保存BP目标实体
	 *
	 * @param target 实体
	 * @return 保存成功否
	 */
	private boolean addBpPerformanceTargetEntity(BpPerformanceTargetEntity target) {
		return baseDao.saveEntity(target);
	}

	/**
	 * 根据月份获取各个省的月度目标
	 *
	 * @param month 月
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTargetByMonth(int month) {
		String param = transMonthToStr(month);
		String sql   = "SELECT province, " + param + " FROM report_bp_performance_target ";
		return baseDao.findObjectsList(sql);
	}

	/**
	 * 根据季度获取各个省的季度目标
	 *
	 * @param quarter 季度
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTargetByQuarter(int quarter) {
		String param = transQuarterToStr(quarter);
		String sql   = "SELECT province, " + param + "  FROM report_bp_performance_target ";
		return baseDao.findObjectsList(sql);
	}

	/*public List<BpPerformanceTargetEntity> listBpPerformanceTargetEntity() {
		String sql = "SELECT * FROM report_bp_performance_target t WHERE t.years=?";
		return baseDao.findEntitys(sql, BpPerformanceTargetEntity.class, getCurrentYear());
	}*/

	/**
	 * 保存月度或季度实体
	 *
	 * @param task 实体
	 * @return 成功
	 */
	private boolean addBpPerformanceTaskEntity(BpPerformanceTaskEntity task) {
		return baseDao.saveEntity(task);
	}

	/**
	 * 清除月度任务数据
	 *
	 * @param year  年
	 * @param month 月
	 * @return 成功
	 */
	private boolean removeBpPerformanceTaskByMonth(int year, int month) {
		String sql = "DELETE FROM report_bp_performance_task WHERE years=? AND months=? AND task_type=0";
		return baseDao.excuteSql(sql, year, month);
	}

	/**
	 * 清除季度任务数据
	 *
	 * @param year    年
	 * @param quarter 季度
	 * @return 成功
	 */
	private boolean removeBpPerformanceTaskByQuarter(int year, int quarter) {
		String sql = "DELETE FROM report_bp_performance_task WHERE years=? AND quarter=? AND task_type=1";
		return baseDao.excuteSql(sql, year, quarter);
	}

	/**
	 * 查询各个省月度数据
	 *
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTaskForMonth(int months) {
		String sql = "SELECT t.province,t.task_amount,t.client_new_count," +
				" t.client_new_amount,t.client_old_count," +
				" t.client_old_amount,t.total_count," +
				" t.total_amount,t.task_complete_ratio," +
				" t.current_issue_rank,t.pre_issue_rank" +
				" FROM report_bp_performance_task t WHERE t.years=? AND t.months=? AND t.task_type=0" +
				" ORDER BY t.total_amount DESC";
		return baseDao.findObjectsList(sql, getCurrentYear(), months);
	}

	/**
	 * 查询各个省季度数据
	 *
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTaskForQuarter(int months) {
		String sql = "SELECT t.province,t.task_amount,t.client_new_count," +
				" t.client_new_amount,t.client_old_count," +
				" t.client_old_amount,t.total_count," +
				" t.total_amount,t.task_complete_ratio," +
				" t.current_issue_rank,t.pre_issue_rank" +
				" FROM report_bp_performance_task t WHERE t.years=? AND t.quarter=? AND t.task_type=1" +
				" ORDER BY t.current_issue_rank, t.total_amount";
		return baseDao.findObjectsList(sql, getCurrentYear(), getCurrentQuarter(months));
	}

	/**
	 * 根据月度数据统计出季度数据
	 *
	 * @param quarter 季度
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTaskQuarterFromMonth(int quarter) {
		int m1, m2, m3;
		m1 = 1;
		m2 = 2;
		m3 = 3;

		if (quarter == 2) {
			m1 = 4;
			m2 = 5;
			m3 = 6;
		} else if (quarter == 3) {
			m1 = 7;
			m2 = 8;
			m3 = 9;
		} else if (quarter == 4) {
			m1 = 10;
			m2 = 11;
			m3 = 12;
		}

		String sql = "SELECT t.province, SUM(t.task_amount), SUM(client_new_count), SUM(client_new_amount)," +
				" SUM(client_old_count), SUM(client_old_amount), SUM(total_count), " +
				" SUM(total_amount) as total_amount, SUM(task_complete_ratio), SUM(current_issue_rank), SUM(pre_issue_rank) " +
				" FROM report_bp_performance_task t WHERE years= ? AND months IN (?,?,?) GROUP BY t.province" +
				" ORDER BY total_amount DESC";
		return baseDao.findObjectsList(sql, getCurrentYear(), m1, m2, m3);
	}

	/*public List<BpPerformanceTaskEntity> listBpPerformanceTaskEntity() {
		String sql = "SELECT * FROM report_bp_performance_task";
		return baseDao.findEntitys(sql, BpPerformanceTaskEntity.class);
	}*/

	/**
	 * 根据传入的月份查询其上期月度排名
	 *
	 * @param months 月
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTaskPreRankForMonth(int months) {
		String sql = "SELECT province, current_issue_rank FROM report_bp_performance_task WHERE months=? and years=?";
		if (months < 1 || months > 12) {
			throw new RuntimeException("月份必须位于1-12之间");
		}
		int years = getCurrentYear();
		if (months == 1) {
			years -= 1;
			months = 12;
		} else {
			months -= 1;
		}

		return baseDao.findObjectsList(sql, months, years);
	}

	/**
	 * 根据传入的月份查询其上期季度排名
	 *
	 * @param months 月
	 * @return 数据
	 */
	private List<Object[]> listBpPerformanceTaskPreRankForQuarter(int months) {
		String sql     = "SELECT province, pre_issue_rank FROM report_bp_performance_task WHERE quarter=? and years=?";
		int    quarter = getCurrentQuarter(months);
		int    years   = getCurrentYear();
		if (quarter == 1) {
			years -= 1;
			quarter = 4;
		} else {
			quarter -= 1;
		}

		return baseDao.findObjectsList(sql, quarter, years);
	}

	/**
	 * 更新新增客户字段
	 *
	 * @param count    贷款次数
	 * @param amount   贷款金额
	 * @param province 省份
	 * @param months   月份
	 * @return 是否成功
	 */
	private boolean updateBpPerformanceTaskNewByProvince(int count, int amount, String province, int months) {
		String sql = "UPDATE report_bp_performance_task SET client_new_count=?, client_new_amount=? " +
				" WHERE province=? and months=? and years=?";
		return baseDao.excuteSql(sql, count, amount, province, months, getCurrentYear());
	}

	/**
	 * 更新续贷客户字段
	 *
	 * @param count    贷款次数
	 * @param amount   贷款金额
	 * @param province 省份
	 * @param months   月份
	 * @return 是否成功
	 */
	private boolean updateBpPerformanceTaskOldByProvince(int count, int amount, String province, int months) {
		String sql = "UPDATE report_bp_performance_task SET client_old_count=?, client_old_amount=? " +
				" WHERE province=?  and months=? and years=?";
		return baseDao.excuteSql(sql, count, amount, province, months, getCurrentYear());
	}

	/**
	 * 更新当前月份排名字段
	 *
	 * @param rank     排名
	 * @param province 省份
	 * @param months   月
	 * @return 更新成功
	 */
	private boolean updateBpPerformanceTaskCurrRankByProvince(int rank, String province, int months) {
		String sql = "UPDATE report_bp_performance_task SET current_issue_rank=? WHERE province=? AND months=? AND years=?";
		return baseDao.excuteSql(sql, rank, province, months, getCurrentYear());
	}

	/**
	 * 更新上期排名字段
	 *
	 * @param rank     排名
	 * @param province 省份
	 * @return 更新成功
	 */
	private boolean updateBpPerformanceTaskPreRankByProvince(int rank, String province) {
		String sql = "UPDATE report_bp_performance_task SET pre_issue_rank=? WHERE province=? AND months=? AND years=?";
		return baseDao.excuteSql(sql, rank, province, getCurrentMonth(), getCurrentYear());
	}

	/**
	 * 各个省当月放款总额和笔数
	 *
	 * @param months 月份
	 * @return 数据
	 */
	private List<Object[]> listServiceTotalData(int months) {
		String sql = "SELECT r.regional_name, SUM(l.bank_amount) as amount, COUNT(1) as total, " +
				" l.loana_mount FROM o2o_loanapply l LEFT JOIN o2o_platform_regional r ON l.ltd=r.platform_id " +
				" WHERE l.loan_flg = 'Y' AND loan_type='BP' AND YEAR(l.payment_time)=? AND MONTH(l.payment_time)=? " +
				" GROUP BY r.regional_name ORDER BY amount desc";

		return serviceDao.findParams(sql, getCurrentYear(), months);
	}

	/**
	 * 各个省传入月份放款总额和笔数（新增客户）
	 *
	 * @param months 月份
	 * @return 数据
	 */
	private List<Object[]> listServiceTotalDataForNewClient(int months) {
		String sql = "SELECT r.regional_name, COUNT(1) as total, SUM(l.bank_amount)/10000 FROM o2o_loanapply l" +
				" LEFT JOIN o2o_platform_regional r ON l.ltd=r.platform_id" +
				" INNER JOIN" +
				" (SELECT l2.loan_id, COUNT(l2.loan_id) AS old FROM o2o_loanapply l2 " +
				" GROUP BY l2.loan_id HAVING COUNT(l2.loan_id)=1) AS l2 ON l2.loan_id=l.loan_id " +
				" WHERE l.loan_flg = 'Y' AND loan_type='BP' AND YEAR(l.payment_time)=? AND MONTH(l.payment_time)=? " +
				" GROUP BY r.regional_name";

		return serviceDao.findParams(sql, getCurrentYear(), months);
	}

	/**
	 * 各个省传入月份放款总额和笔数（续贷客户）
	 *
	 * @param months 月份
	 * @return 数据
	 */
	private List<Object[]> listServiceTotalDataForOldClient(int months) {
		String sql = "SELECT r.regional_name, COUNT(1) as total, SUM(l.bank_amount)/10000 FROM o2o_loanapply l" +
				" LEFT JOIN o2o_platform_regional r ON l.ltd=r.platform_id" +
				" INNER JOIN" +
				" (SELECT l2.loan_id, COUNT(l2.loan_id) AS old FROM o2o_loanapply l2 " +
				" GROUP BY l2.loan_id HAVING COUNT(l2.loan_id)>1) AS l2 ON l2.loan_id=l.loan_id " +
				" WHERE l.loan_flg = 'Y' AND loan_type='BP' AND YEAR(l.payment_time)=? AND MONTH(l.payment_time)=? " +
				" GROUP BY r.regional_name";

		return serviceDao.findParams(sql, getCurrentYear(), months);
	}

	public Integer getCurrentMonth() {
		return LocalDate.now().getMonthValue();
	}

	public Integer getCurrentYear() {
		return LocalDate.now().getYear();
	}

	/**
	 * 获取当前季度数
	 *
	 * @param month 月份
	 * @return 季度
	 */
	private Integer getCurrentQuarter(int month) {
		return getQuarter(month);
	}

	/**
	 * 取得月份所对应的季度数
	 *
	 * @param month 月份
	 * @return 季度
	 */
	private Integer getQuarter(int month) {
		Integer q = month / 3;
		return month % 3 > 0 ? ++q : q;
	}

	/**
	 * 将季度数值转换为数据库对应的字段
	 *
	 * @param quarter 季度（q1,q2,q3,q4）
	 */
	private String transQuarterToStr(int quarter) {
		String p1 = "1";
		switch (quarter) {
			case 1:
				p1 = "q1";
				break;
			case 2:
				p1 = "q2";
				break;
			case 3:
				p1 = "q3";
				break;
			case 4:
				p1 = "q4";
				break;
		}
		return p1;
	}


	/**
	 * 将月份转换为数据库对应的字段
	 *
	 * @param month 月
	 */
	private String transMonthToStr(int month) {
		String p1 = "1";
		switch (month) {
			case 1:
				p1 = "jan";
				break;
			case 2:
				p1 = "feb";
				break;
			case 3:
				p1 = "mar";
				break;
			case 4:
				p1 = "apr";
				break;
			case 5:
				p1 = "may";
				break;
			case 6:
				p1 = "jun";
				break;
			case 7:
				p1 = "jul";
				break;
			case 8:
				p1 = "aug";
				break;
			case 9:
				p1 = "sep";
				break;
			case 10:
				p1 = "oct";
				break;
			case 11:
				p1 = "nov";
				break;
			case 12:
				p1 = "dec";
				break;
		}
		return p1;
	}

	/**
	 * 初始化全国各省区品牌贷投放情况：月度和季度任务指标
	 */
	public void initBpPerformanceTarget() {
		HSSFWorkbook wb;
		try {
			wb = new HSSFWorkbook(this.getClass().getResourceAsStream("/excelTemplate/report_bp_performance.xls"));
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("初始化全国各省区品牌贷投放情况：月度和季度任务指标失败。异常【{}】", e);
			return;
		}
		HSSFSheet            sheet     = wb.getSheetAt(2);
		HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);

		for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
			if (rowNum >= 3) {
				HSSFRow                   row    = sheet.getRow(rowNum);
				BpPerformanceTargetEntity target = new BpPerformanceTargetEntity();
				target.setProvince(row.getCell(1).toString());
				target.setYear(getCurrentYear());
				target.setJan((int) row.getCell(2).getNumericCellValue());
				target.setFeb((int) row.getCell(3).getNumericCellValue());
				target.setMar((int) row.getCell(4).getNumericCellValue());
				target.setQ1((int) evaluator.evaluate(row.getCell(5)).getNumberValue());

				target.setApr((int) row.getCell(6).getNumericCellValue());
				target.setMay((int) row.getCell(7).getNumericCellValue());
				target.setJun((int) row.getCell(8).getNumericCellValue());
				target.setQ2((int) evaluator.evaluate(row.getCell(9)).getNumberValue());

				target.setJul((int) row.getCell(10).getNumericCellValue());
				target.setAug((int) row.getCell(11).getNumericCellValue());
				target.setSep((int) row.getCell(12).getNumericCellValue());
				target.setQ3((int) evaluator.evaluate(row.getCell(13)).getNumberValue());

				target.setOct((int) row.getCell(14).getNumericCellValue());
				target.setNov((int) row.getCell(15).getNumericCellValue());
				target.setDec((int) row.getCell(16).getNumericCellValue());
				target.setQ4((int) evaluator.evaluate(row.getCell(17)).getNumberValue());
				target.setTotal((int) row.getCell(18).getNumericCellValue());

				addBpPerformanceTargetEntity(target);
			}
		}
	}

	/**
	 * 生成BP报表
	 *
	 * @throws FileNotFoundException 模板文件未找到
	 */
	public void generateBpReport(int month) throws FileNotFoundException {
		InputStream input     = this.getClass().getResourceAsStream("/excelTemplate/report_bp_performance.xls");
		int         currMonth = getCurrentMonth();
		if (month >= 1 && month <= 12) {
			currMonth = month;
		}

		String              monthTitle   = "全国各省区品牌贷投放情况（" + getCurrentYear() + "年" + currMonth + "月 ）";
		List<Object[]>      monthData    = listBpPerformanceTaskForMonth(currMonth);
		BankRowWriteHandler monthHandler = new BankRowWriteHandler(monthData, 12, null, Collections.singletonList(monthTitle), 0, 5, 1);

		String              quarterTitle   = "全国各省区品牌贷投放情况（" + getCurrentYear() + "年第" + getCurrentQuarter(currMonth) + "季度 ）";
		List<Object[]>      quarterData    = listBpPerformanceTaskForQuarter(currMonth);
		BankRowWriteHandler quarterHandler = new BankRowWriteHandler(quarterData, 12, null, Collections.singletonList(quarterTitle), 1, 5, 1);

		StringBuilder outPath = new StringBuilder(outpath);
		outPath.append(File.separator).append(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		outPath.append(File.separator).append("品牌贷--品牌贷投放月度考核和季度考核").append(".xls");
		IoUtil.createDirectorieIfMissing(new File(outPath.toString()).getParentFile());
		FileOutputStream output = new FileOutputStream(outPath.toString());

		ExcelApiHelper.writeHandle(output, input, monthHandler, quarterHandler);
	}

	/**
	 * 品牌贷--品牌贷投放月度考核和季度考核报表发送
	 */
	public void bpPerformanceReportSend() {
		String title = "品牌贷投放月度考核和季度考核报表";
		String date  = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

		EmailContentEntity entity = new EmailContentEntity();
		entity.setHost(emailSourceSetting.getHost());
		entity.setUsername(emailSourceSetting.getFrom());
		entity.setPassword(emailSourceSetting.getPassword());
		entity.setFrom(emailSourceSetting.getFrom());
		entity.setSubject(title + date);
		entity.setContent(title + date);

		//报表存储路径
		StringBuilder path = new StringBuilder(outpath);
		path.append(File.separator).append(date);
		ArrayList<String> dirs = new ArrayList<>();
		dirs.add(path.toString());
		//list去重
		HashSet<String> h = new HashSet<>(dirs);
		dirs.clear();
		dirs.addAll(h);
		entity.setAttachmentDirectories(dirs);

		String[] receivers = emailSourceSetting.getToCreditManager().split(",");
		for (String receiver : receivers) {
			entity.setTo(receiver);
			emailSender.send(entity);
		}
	}

	/**
	 * 初始化currMonth月各个省的月度task
	 *
	 * @param currYear  年
	 * @param currMonth 月
	 */
	public void initTaskOfTheMonths(int currYear, int currMonth) {
		Map<String, Object[]> totalMap = new HashMap<>();
		//取出全年当月指标
		List<Object[]> targetList = listBpPerformanceTargetByMonth(currMonth);

		//清除当年当月的数据
		removeBpPerformanceTaskByMonth(currYear, currMonth);

		//1.从Service查询各个省月度【全部】放贷金额，笔数，当前排名
		List<Object[]> serviceTotalData = listServiceTotalData(currMonth);
		for (int i = 0; i < serviceTotalData.size(); i++) {
			Object[] obj = serviceTotalData.get(i);
			obj[1] = ((BigDecimal) obj[1]).divide(new BigDecimal("10000"), 0, BigDecimal.ROUND_HALF_DOWN);
			obj[3] = i + 1;
			totalMap.put((String) obj[0], obj);
		}
		//2.初始当月月度任务
		for (Object[] target : targetList) {
			BpPerformanceTaskEntity task     = new BpPerformanceTaskEntity();
			String                  province = (String) target[0];
			task.setProvince(province);
			task.setYear(currYear);
			task.setMonth(currMonth);
			task.setQuarter(getCurrentQuarter(currMonth));
			task.setTaskType(0);
			task.setTaskAmount((int) target[1]);

			Object[] totalTask = totalMap.get(province);
			if (null != totalTask) {
				task.setTotalAmount(((BigDecimal) totalTask[1]).intValue());
				task.setTotalCount(((Long) totalTask[2]).intValue());
				int rank = (int) totalTask[3];
				task.setCurrentIssueRank(0 != rank ? rank : 0);

				BigDecimal completeAmount = (BigDecimal) totalTask[1];
				BigDecimal totalAmount    = new BigDecimal((int) target[1] + "");
				BigDecimal ratio          = new BigDecimal("0");
				if (0 != totalAmount.intValue()) {
					ratio = completeAmount.multiply(new BigDecimal("100")).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
				}
				task.setTaskCompleteRatio(ratio.toString() + "%");
			} else {
				task.setTotalAmount(0);
				task.setTotalCount(0);
				task.setCurrentIssueRank(0);
				task.setTaskCompleteRatio("0%");
			}

			addBpPerformanceTaskEntity(task);
		}
		//再次计算排名
		List<Object[]> monthData = listBpPerformanceTaskForMonth(currMonth);
		for (int i = 0; i < monthData.size(); i++) {
			updateBpPerformanceTaskCurrRankByProvince(i + 1, (String) monthData.get(i)[0], currMonth);
		}

		//3.从DEV查询各个省月度上期排名并入库
		listBpPerformanceTaskPreRankForMonth(currMonth).stream().filter(obj -> null != obj).forEach(obj -> updateBpPerformanceTaskPreRankByProvince((int) obj[1], (String) obj[0]));
		//4.从Service查询各个省月度【新增客户】放贷金额和笔数并入库
		listServiceTotalDataForNewClient(currMonth).forEach(obj -> updateBpPerformanceTaskNewByProvince(((Long) obj[1]).intValue(),
				((BigDecimal) obj[2]).intValue(), (String) obj[0], currMonth));

		//5.从Service查询各个省月度【续贷客户】放贷金额和笔数并入库
		listServiceTotalDataForOldClient(currMonth).forEach(obj -> updateBpPerformanceTaskOldByProvince(((Long) obj[1]).intValue(),
				((BigDecimal) obj[2]).intValue(), (String) obj[0], currMonth));
	}

	/**
	 * 初始化currMonth月各个省的季度task
	 *
	 * @param currYear  年
	 * @param currMonth 月
	 */
	public void initTaskOfTheQuarter(int currYear, int currMonth) {
		int                   currQuarter = getCurrentQuarter(currMonth);
		Map<String, Object[]> totalMap    = new HashMap<>();
		//取出全年当季度指标
		List<Object[]> targetList = listBpPerformanceTargetByQuarter(currQuarter);

		//清除当年当季度的数据
		removeBpPerformanceTaskByQuarter(currYear, currQuarter);

		//1.根据当前季度的月份统计出季度数据
		for (int i = 0; i < listBpPerformanceTaskQuarterFromMonth(currQuarter).size(); i++) {
			Object[] obj = listBpPerformanceTaskQuarterFromMonth(currQuarter).get(i);
			obj[9] = i + 1;
			totalMap.put((String) obj[0], obj);
		}

		//2.初始当季度任务
		for (Object[] target : targetList) {
			BpPerformanceTaskEntity task     = new BpPerformanceTaskEntity();
			String                  province = (String) target[0];
			task.setProvince(province);
			task.setYear(currYear);
			task.setMonth(currMonth);
			task.setQuarter(currQuarter);
			task.setTaskType(1);
			task.setTaskAmount((int) target[1]);

			Object[] totalTask = totalMap.get(province);
			if (null != totalTask) {
				task.setClientNewCount(((BigDecimal) totalTask[2]).intValue());
				task.setClientNewAmount(((BigDecimal) totalTask[3]).intValue());
				task.setClientOldCount(((BigDecimal) totalTask[4]).intValue());
				task.setClientOldAmount(((BigDecimal) totalTask[5]).intValue());
				task.setTotalCount(((BigDecimal) totalTask[6]).intValue());
				task.setTotalAmount(((BigDecimal) totalTask[7]).intValue());
				task.setCurrentIssueRank((int) totalTask[9]);

				BigDecimal completeAmount = (BigDecimal) totalTask[7];
				BigDecimal totalAmount    = new BigDecimal((int) target[1] + "");
				BigDecimal ratio          = new BigDecimal("0");
				if (0 != totalAmount.intValue()) {
					ratio = completeAmount.multiply(new BigDecimal("100")).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
				}
				task.setTaskCompleteRatio(ratio.toString() + "%");
			} else {
				task.setClientNewCount(0);
				task.setClientNewAmount(0);
				task.setClientOldCount(0);
				task.setClientOldAmount(0);
				task.setTotalAmount(0);
				task.setTotalCount(0);
				task.setCurrentIssueRank(0);
				task.setTaskCompleteRatio("0%");
			}

			//3.查询上季度排名并更新
			listBpPerformanceTaskPreRankForQuarter(currMonth).stream().filter(obj -> null != obj).forEach(obj -> updateBpPerformanceTaskPreRankByProvince((int) obj[1], (String) obj[0]));

			addBpPerformanceTaskEntity(task);
		}
	}
}
